<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      v-show="showSearch"
      :inline="true"
    >
      <el-form-item label="所属系统" prop="group">
        <el-input
          v-model="queryParams.group"
          placeholder="请输入所属系统"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:api:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:api:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="single"
          @click="handleDelete"
          v-hasPermi="['system:api:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="tableList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属系统" prop="group" />
      <el-table-column label="名称" prop="name" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span
            style="color: #1890ff; cursor: pointer"
            @click="excuteLogok(scope.row)"
            >{{ scope.row.name }}</span
          >
        </template>
      </el-table-column>
      <el-table-column
        label="cron表达式"
        prop="cron"
        :show-overflow-tooltip="true"
        width="180"
      />
      <el-table-column label="状态" prop="status" :show-overflow-tooltip="true" width="160">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == '正常'" type="" effect="dark">正常</el-tag>
          <el-tag v-else-if="scope.row.status == '故障'" type="danger" effect="dark">故障</el-tag>
          <el-tag v-else type="" effect="plain">--</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="可用率"
        prop="usability"
        :show-overflow-tooltip="true"
        width="160"
      />
      <el-table-column
        label="平均响应时间"
        prop="avgCostTime"
        :show-overflow-tooltip="true"
        width="160"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="230"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            :icon="
              scope.row.isEnabled ? 'el-icon-video-pause' : 'el-icon-video-play'
            "
            @click="handleStartStop(scope.row)"
            v-hasPermi="['system:api:startstop']"
            >{{ scope.row.isEnabled ? "停止" : "启动" }}</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="handleexcuteApi(scope.row)"
            v-hasPermi="['system:api:excute']"
            >执行一次</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:api:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:api:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body
      :before-close="cancel"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="所属系统" prop="group">
          <el-select
            v-model="form.group"
            placeholder="请选择所属系统"
            style="width: 80%"
          >
            <el-option
              v-for="(item, index) in groupList"
              :key="index"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
          <el-button
            style="float: right"
            type="primary"
            icon="el-icon-plus"
            @click="addGroup"
          ></el-button>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="API管理">
          <div
            style="
              display: flex;
              justify-content: space-between;
              margin-bottom: 10px;
            "
          >
            <el-button type="primary" @click="apiTest">测试API</el-button
            ><el-button
              type="primary"
              icon="el-icon-plus"
              @click="addAPI"
            ></el-button>
          </div>
          <el-table :data="form.httpRequest" style="width: 100%" size="mini">
            <el-table-column type="index" label="编号" width="60">
            </el-table-column>
            <el-table-column prop="name" label="API名称" width="100">
            </el-table-column>
            <el-table-column prop="httpMethod" label="API类型" width="100">
            </el-table-column>
            <el-table-column prop="url" label="API地址"> </el-table-column>
            <el-table-column prop="generalSituation" label="概况">
              <template slot-scope="scope">
                <span
                  ><span style="color: red">{{
                    scope.row.headers
                      ? scope.row.headers.match(/::/g).length
                      : 0
                  }}</span
                  >请求头，</span
                >
                <span
                  ><span style="color: red">{{
                    scope.row.parameters
                      ? scope.row.parameters.match(/::/g).length
                      : 0
                  }}</span
                  >参数，</span
                >
                <span
                  ><span style="color: red">{{
                    scope.row.body && Object.keys(scope.row.body).length ? 1 : 0
                  }}</span
                  >请求体，</span
                >
                <span
                  ><span style="color: red">{{
                    scope.row.variables
                      ? scope.row.variables.match(/::/g).length
                      : 0
                  }}</span
                  >变量</span
                >
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template slot-scope="scope">
                <el-button
                  @click="editRow(scope.row)"
                  type="text"
                  size="small"
                  icon="el-icon-edit"
                >
                </el-button>
                <el-button
                  @click="deleteRow(scope.$index)"
                  type="text"
                  size="small"
                  icon="el-icon-delete"
                >
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="数据表" prop="dockDataConfig.tableName" v-if="form.jobType == 'DOCKDATA'">
          <el-input
            v-model="form.dockDataConfig.tableName"
            placeholder="请输入数据表"
            @change="changetableName"
          ></el-input>
        </el-form-item>
        <el-form-item label="数据源" prop="dockDataConfig.dataSource" v-if="form.jobType == 'DOCKDATA'">
          <el-select
            v-model="form.dockDataConfig.dataSource"
            placeholder="请选择数据源"
            style="width: 100%"
            @change="changedatasource"
          >
            <el-option
              v-for="(item, index) in datasourceArr"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="字段映射" prop="dockDataConfig.mappingRelation" v-if="form.jobType == 'DOCKDATA'">
          <el-row
            style="
              color: #515a6e;
              font-size: 13px;
              background-color: #f8f8f9;
              height: 48px;
              line-height: 48px;
              font-weight: bolder;
              border-bottom: 1px solid #dfe6ec;
            "
          >
            <el-col :span="6" style="padding-left: 10px">源字段</el-col>
            <el-col :span="6" style="padding-left: 10px">类型</el-col>
            <el-col :span="6" style="padding-left: 10px">目标字段</el-col>
            <el-col :span="6" style="padding-left: 10px">目标值</el-col>
          </el-row>
          <el-row
            v-for="(item, index) in form.dockDataConfig.mappingRelation"
            :key="index"
            style="
              margin-top: 5px;
              padding-bottom: 5px;
              border-bottom: 1px solid #dfe6ec;
            "
          >
            <el-col :span="6" style="padding-left: 10px">{{
              item.column_name
            }}</el-col>
            <el-col :span="6" style="padding-left: 10px">
              <el-select
                v-model="item.column_type"
                placeholder="请选择类型"
                @change="changeColumntype(item)"
              >
                <el-option label="静态" value="STATIC"></el-option>
                <el-option label="动态" value="DYNAMIC"></el-option>
                <el-option label="函数" value="FUNCTION"></el-option>
              </el-select>
            </el-col>
            <el-col :span="6" style="padding-left: 10px"
              ><el-input
                v-model="item.column_key"
                placeholder="请输入内容"
              ></el-input
            ></el-col>
            <el-col :span="6" style="padding-left: 10px"
              ><el-input
                :disabled="item.column_type === 'DYNAMIC'"
                v-model="item.column_value"
                placeholder="请输入内容"
              ></el-input
            ></el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="批量入库规则" prop="dockDataConfig.batchLimit" v-if="form.jobType == 'DOCKDATA'">
          <el-select
            v-model="form.dockDataConfig.batchLimit"
            placeholder="请选择批量入库规则"
            style="width: 100%"
          >
            <el-option label="100" :value="100"></el-option>
            <el-option label="200" :value="200"></el-option>
            <el-option label="300" :value="300"></el-option>
            <el-option label="400" :value="400"></el-option>
            <el-option label="500" :value="500"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否循环入库规则" prop="dockDataConfig.isWhile" v-if="form.jobType == 'DOCKDATA'">
          <el-radio-group
            v-model="form.dockDataConfig.isWhile"
            @input="changeisWhile"
          >
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="循环规则"
          prop="dockDataConfig.whileRule"
          v-show="form.dockDataConfig.isWhile === 1"
        >
          <el-input
            type="textarea"
            v-model="form.dockDataConfig.whileRule"
            placeholder="请输入循环规则"
          ></el-input>
        </el-form-item>
        <el-form-item label="入库前是否执行清除" prop="dockDataConfig.isClean" v-if="form.jobType == 'DOCKDATA'">
          <el-radio-group
            v-model="form.dockDataConfig.isClean"
            @input="changeisClean"
          >
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="清除规则"
          prop="dockDataConfig.cleanRule"
          v-show="form.dockDataConfig.isClean === 1"
        >
          <el-input
            type="textarea"
            v-model="form.dockDataConfig.cleanRule"
            placeholder="请输入清除规则"
          ></el-input>
        </el-form-item>
        <el-form-item label="cron表达式" prop="dockDataConfig.cron">
          <el-input
            v-model="form.dockDataConfig.cron"
            placeholder="请输入cron表达式"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="form.remark"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type" v-show="false">
          <el-input v-model="form.type" placeholder="请输入类型"></el-input>
        </el-form-item>
        <el-form-item label="频率" prop="frequency" v-show="false">
          <el-input
            v-model="form.frequency"
            placeholder="请输入频率"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改api -->
    <el-dialog
      :title="apititle"
      :visible.sync="apiopen"
      width="800px"
      append-to-body
      :before-close="apicancel"
    >
      <el-form
        ref="apiform"
        :model="apiform"
        :rules="apirules"
        label-width="80px"
      >
        <el-form-item label="API类型" prop="httpMethod">
          <el-radio-group v-model="apiform.httpMethod">
            <el-radio label="GET">GET</el-radio>
            <el-radio label="POST">POST</el-radio>
            <el-radio label="HEAD">HEAD</el-radio>
            <el-radio label="PUT">PUT</el-radio>
            <el-radio label="DELETE">DELETE</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="API名称" prop="name">
          <el-input v-model="apiform.name" placeholder="请输入API名称" />
        </el-form-item>
        <el-form-item label="API地址" prop="url">
          <el-input v-model="apiform.url" placeholder="请输入API地址" />
        </el-form-item>
        <el-form-item label="请求头部" prop="headers">
          <el-input
            type="textarea"
            v-model="apiform.headers"
            placeholder="头部key::头部value
头部key::头部value"
          ></el-input>
        </el-form-item>
        <el-form-item label="请求参数" prop="parameters">
          <el-input
            type="textarea"
            v-model="apiform.parameters"
            placeholder="参数key::参数value
参数key::参数value"
          ></el-input>
        </el-form-item>
        <el-form-item label="请求体" prop="body">
          <vue-json-editor
            v-model="apiform.body"
            :showBtns="false"
            :mode="'code'"
            lang="zh"
            :expandedOnStart="false"
            @json-change="jsonChange"
            @json-save="jsonSave"
            @has-error="hasError"
          />
        </el-form-item>
        <el-form-item label="结果校验">
          <el-row>
            <el-col :span="6">
              <el-select
                v-model="apiform.conditionType"
                placeholder="请选择校验类型"
                style="width: 100%"
              >
                <el-option label="无" value="DEFAULT"></el-option>
                <el-option label="响应码" value="STATUSCODE"></el-option>
                <el-option label="内容包含" value="CONTAINS"></el-option>
                <el-option
                  label="内容不包含"
                  value="DOESNT_CONTAIN"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="1" style="text-align: center">-</el-col>
            <el-col :span="17"
              ><el-input
                v-model="apiform.condition"
                placeholder="请输入数据表"
              ></el-input
            ></el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="结果提取">
          <el-radio-group v-model="apiform.resultType">
            <el-radio label="XML">xPath</el-radio>
            <el-radio label="JSON">jsonPath</el-radio>
            <el-radio :label="null">无</el-radio>
          </el-radio-group>
          <span
            style="
              display: inline-block;
              float: right;
              mrgin-left: 30px;
              color: #1890ff;
              cursor: pointer;
            "
            @click="openTutorials"
            >查看xPath和jsonPath的使用教程</span
          >
          <el-input
            type="textarea"
            v-model="apiform.variables"
            placeholder="$$变量名::xPath路径
$$变量名::xPath路径"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAPI">确 定</el-button>
        <el-button @click="apicancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 测试api结果查看 -->
    <el-dialog
      title="测试API结果"
      :visible.sync="apiTestopen"
      width="80%"
      append-to-body
      :before-close="apiTestcancel"
    >
      <el-table :data="apiTestData" style="width: 100%">
        <el-table-column type="index" label="序号" width="60">
        </el-table-column>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <div style="width: 100%; height: 400px; overflow: auto">
              <pre>{{
                scope.row.responseBody
                  ? JSON.parse(scope.row.responseBody)
                  : scope.row.responseBody
              }}</pre>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="API名称" width="100">
        </el-table-column>
        <el-table-column prop="url" label="API地址" width="300">
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
        </el-table-column>
        <el-table-column prop="statusCode" label="状态码" width="100">
        </el-table-column>
        <el-table-column prop="costTime" label="响应时间" width="100">
          <template slot-scope="scope">
            <span>{{
              scope.row.costTime ? scope.row.costTime + "毫秒" : ""
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="responseBody"
          show-overflow-tooltip
          label="响应结果"
        >
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="apiTestcancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 执行日志 -->
    <el-dialog
      title="执行日志"
      :visible.sync="excuteLogopen"
      width="80%"
      append-to-body
      :before-close="excuteLogcancel"
    >
      <el-table :data="excuteLogData" style="width: 100%">
        <el-table-column type="index" label="序号" width="60">
        </el-table-column>
        <el-table-column prop="createTime" label="监控时间" width="180">
          <template slot-scope="scope">
            <span>{{
              scope.row.createTime
                ? scope.row.createTime.indexOf("T") > -1
                  ? scope.row.createTime.replace("T", " ")
                  : ""
                : ""
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.status ? "正常" : "故障" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="costTime" label="响应时间" width="130">
          <template slot-scope="scope">
            <span>{{
              scope.row.costTime ? scope.row.costTime + "毫秒" : ""
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="log" label="日志"> </el-table-column>
        <el-table-column label="API详情" width="80">
          <template slot-scope="scope">
            <el-button
              @click="apiLogok(scope.row)"
              type="text"
              size="small"
              icon="el-icon-view"
            >
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="excuteLogTotal > 0"
        :total="excuteLogTotal"
        :page.sync="excuteLogParams.pageNum"
        :limit.sync="excuteLogParams.pageSize"
        @pagination="excuteLog"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="excuteLogcancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 接口调用日志 -->
    <el-dialog
      title="接口调用日志"
      :visible.sync="apiLogopen"
      width="80%"
      append-to-body
      :before-close="apiLogcancel"
    >
      <el-table :data="apiLogData" style="width: 100%">
        <el-table-column type="index" label="序号" width="60">
        </el-table-column>
        <el-table-column prop="name" label="API名称" width="120">
        </el-table-column>
        <el-table-column prop="httpMethod" label="API类型" width="120">
        </el-table-column>
        <el-table-column prop="url" label="API地址"> </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.status ? "正常" : "故障" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="statusCode" label="响应状态码" width="120">
        </el-table-column>
        <el-table-column prop="costTime" label="响应时间" width="130">
          <template slot-scope="scope">
            <span>{{
              scope.row.costTime ? scope.row.costTime + "毫秒" : ""
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="log" label="日志"> </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="apiLogcancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  dockList,
  dockDeleteMonitor,
  getGroups,
  addGroup,
  editSequenceMonitor,
  datasourceList,
  datasourceFields,
  saveSequenceMonitor,
  testApi,
  excuteApi,
  enableMonitor,
  apiLog,
  excuteLog,
} from "@/api/monitor/api";
import vueJsonEditor from "vue-json-editor";
export default {
  name: "Role",
  components: { vueJsonEditor },
  data() {
    var validateCron = (rule, value, callback) => {
      const cronParse = require("cron-parser");
      if (value) {
        try {
          const interval = cronParse.parseExpression(value);
          console.log("cronDate:", interval.next().toDate());
        } catch (e) {
          callback("非Cron表达式格式，请检查！" + e.message);
        }
      } else {
        callback("Cron表达式不能为空！");
      }
      callback();
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      tableList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        group: "",
        name: "",
        jobType: "MONITOR",
        guid: this.$route.query.guid
      },
      // 表单参数
      form: {
        group: undefined,
        name: "",
        remark: "",
        type: "SEQUENCE",
        frequency: "ONE_DAY",
        httpRequest: [],
        jobType: "MONITOR",
        dockDataConfig: {
          tableName: "",
          dataSource: undefined,
          mappingRelation: [],
          batchLimit: undefined,
          isWhile: 0,
          whileRule: "",
          isClean: 0,
          cleanRule: "",
          cron: "0 0 0 * * ?",
        },
      },
      // 表单校验
      rules: {
        group: [
          { required: true, message: "请选择所属系统", trigger: "change" },
        ],
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        "dockDataConfig.cron": [
          { required: true, validator: validateCron, trigger: "blur" },
        ],
      },
      groupList: [],
      datasourceArr: [],

      apititle: "添加API",
      apiopen: false,
      apiform: {
        httpMethod: "GET",
        url: "",
        headers: "",
        parameters: "",
        body: {},
        conditionType: "DEFAULT",
        condition: "",
        resultType: null,
        variables: "",
        sort: "",
        name: ""
      },
      apirules: {
        httpMethod: [
          { required: true, message: "请选择API类型", trigger: "change" },
        ],
        url: [{ required: true, message: "API地址不能为空", trigger: "blur" }],
        name: [{ required: true, message: "API名称不能为空", trigger: "blur" }]
      },
      apiTestData: [],
      apiTestopen: false,

      apiLogData: [],
      apiLogopen: false,

      excuteLogData: [],
      excuteLogopen: false,
      excuteLogParams: {
        guid: "",
        pageNum: 1,
        pageSize: 10,
      },
      excuteLogTotal: 0,
    };
  },
  created() {
    this.getGroups();
    this.datasourceList();
    this.datasourceFields();
    this.getList();
  },
  methods: {
    // 获取所属系统
    getGroups() {
      getGroups().then((response) => {
        this.groupList = response.data;
      });
    },
    // 添加所属系统
    addGroup() {
      this.$prompt("所属系统", "新增", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "请输入系统名称",
        inputValidator: (value) => {
          if (!value) return false;
        },
        inputErrorMessage: "请输入系统名称",
      })
        .then(({ value }) => {
          addGroup({ systemName: value }).then((response) => {
            this.getGroups();
            this.$message({
              type: "success",
              message: "添加成功",
            });
          });
        })
        .catch(() => {});
    },
    // 获取数据源
    datasourceList() {
      datasourceList().then((response) => {
        this.datasourceArr = response.data;
      });
    },
    //修改数据表
    changetableName(value) {
      let obj = {
        tableName: value,
        datasource: this.form.dockDataConfig.dataSource
          ? this.form.dockDataConfig.dataSource
          : "",
      };
      this.datasourceFields(obj);
    },
    //修改数据源
    changedatasource(value) {
      let obj = {
        tableName: this.form.dockDataConfig.tableName
          ? this.form.dockDataConfig.tableName
          : "",
        datasource: value,
      };
      this.datasourceFields(obj);
    },
    // 获取字段映射
    datasourceFields(obj) {
      datasourceFields(obj).then((response) => {
        this.form.dockDataConfig.mappingRelation = [];
        response.data.map((item, index) => {
          item.column_value = "";
          item.column_type = "DYNAMIC";
          item.column_key = item.column_name;
        });
        this.form.dockDataConfig.mappingRelation = response.data;
      });
    },
    // 修改是否循环入库规则
    changeisWhile(value) {
      if (value === 0) {
        this.form.dockDataConfig.whileRule = "";
      }
    },
    // 修改入库前是否执行清除
    changeisClean(value) {
      if (value === 0) {
        this.form.dockDataConfig.cleanRule = "";
      }
    },
    // 编辑api
    editRow(row) {
      this.apiform = JSON.parse(JSON.stringify(row));
      this.apititle = "修改API";
      this.apiopen = true;
    },
    // 删除api
    deleteRow(index) {
      this.form.httpRequest.splice(index, 1);
      this.form.httpRequest.map((item, index) => {
        item.sort = index + 1;
      });
    },
    // 打开api
    addAPI() {
      this.resetApiform();
      this.apititle = "添加API";
      this.apiopen = true;
    },
    // 关闭api
    apicancel() {
      this.apiopen = false;
      this.resetApiform();
    },
    // 新增或修改api
    submitAPI() {
      this.$refs["apiform"].validate((valid) => {
        if (valid) {
          if (this.apititle === "添加API") {
            let obj = JSON.parse(JSON.stringify(this.apiform));
            obj.sort = this.form.httpRequest.length + 1;
            this.form.httpRequest.push(obj);
            this.apicancel();
          } else {
            let obj = JSON.parse(JSON.stringify(this.apiform));
            this.form.httpRequest.map((item, index) => {
              if (item.sort === obj.sort) {
                this.form.httpRequest.splice(index, 1, obj);
              }
            });
            this.apicancel();
          }
        }
      });
    },
    // 重置apiform
    resetApiform() {
      this.apiform = {
        httpMethod: "GET",
        url: "",
        headers: "",
        parameters: "",
        body: {},
        conditionType: "DEFAULT",
        condition: "",
        resultType: null,
        variables: "",
        sort: "",
      };
      this.resetForm("apiform");
    },
    /** 查询api列表 */
    getList() {
      this.loading = true;
      dockList(this.queryParams).then((response) => {
        this.tableList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.guid);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const guid = row.guid || this.ids[0];
      editSequenceMonitor({ guid: guid }).then((response) => {
        this.form = response.data.form;
        this.form.httpRequest = this.form.httpRequest
          ? this.form.httpRequest
          : [];
        if (this.form.httpRequest) {
          this.form.httpRequest.map((item) => {
            if (item.body) {
              item.body = JSON.parse(item.body);
            } else {
              item.body = {};
            }
          });
        }
        this.form.dockDataConfig = this.form.dockDataConfig
          ? this.form.dockDataConfig
          : {
              tableName: "",
              dataSource: undefined,
              mappingRelation: [],
              batchLimit: undefined,
              isWhile: 0,
              whileRule: "",
              isClean: 0,
              cleanRule: "",
              cron: "",
            };
        if (this.form.dockDataConfig.mappingRelation) {
          let obj = JSON.parse(this.form.dockDataConfig.mappingRelation);
          let arr = [];
          for (let key in obj) {
            arr.push({
              column_name: key,
              column_key: obj[key]["key"],
              column_type: obj[key]["type"],
              column_value: obj[key]["value"],
            });
          }
          this.form.dockDataConfig.mappingRelation = arr;
        }
        this.open = true;
        this.title = "编辑";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let obj = JSON.parse(JSON.stringify(this.form));
          let new_mappingRelation = {};
          obj.dockDataConfig.mappingRelation.map((item, index) => {
            new_mappingRelation[item.column_name] = {
              key: item.column_key,
              type: item.column_type,
              value: item.column_value,
            };
          });
          obj.dockDataConfig.mappingRelation =
            JSON.stringify(new_mappingRelation);
          if (obj.httpRequest) {
            obj.httpRequest.forEach((item) => {
              if (item.body && Object.keys(item.body).length) {
                item.body = JSON.stringify(item.body);
              } else {
                item.body = null;
              }
              if (!item.resultType) {
                item.variables = "";
              }
              delete item.headersMap;
              delete item.parametersMap;
              delete item.variablesMap;
              delete item.bodyMap;
            });
          }
          saveSequenceMonitor(obj).then((response) => {
            this.$message({
              message: obj.guid ? "修改成功" : "新增成功",
              type: "success",
            });
            this.cancel();
            this.getList();
          });
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        group: undefined,
        name: "",
        remark: "",
        type: "SEQUENCE",
        frequency: "ONE_DAY",
        httpRequest: [],
        jobType: "MONITOR",
        dockDataConfig: {
          tableName: "",
          dataSource: undefined,
          mappingRelation: [],
          batchLimit: undefined,
          isWhile: 0,
          whileRule: "",
          isClean: 0,
          cleanRule: "",
          cron: "0 0 0 * * ?",
        },
      };
      this.resetForm("form");
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let self = this;
      const guids = row.guid || self.ids[0];
      self
        .$confirm('是否确认删除编号为"' + guids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(function () {
          return dockDeleteMonitor({ guid: guids });
        })
        .then(() => {
          self.getList();
          self.$message({
            message: "删除成功",
            type: "success",
          });
        })
        .catch(() => {});
    },
    // 启停
    handleStartStop(row) {
      let self = this;
      self
        .$confirm(row.isEnabled ? "是否确认停止?" : "是否确认启动?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(function () {
          return enableMonitor({
            guid: row.guid,
            enabled: row.isEnabled ? true : false,
          });
        })
        .then(() => {
          self.$message({
            message: row.isEnabled ? "停止成功" : "启动成功",
            type: "success",
          });
          self.getList();
        })
        .catch(() => {});
    },
    // 执行一次
    handleexcuteApi(row) {
      let self = this;
      self
        .$confirm("是否确认执行一次?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(function () {
          return excuteApi({ guid: row.guid });
        })
        .then(() => {
          self.getList();
          self.$message({
            message: "执行成功",
            type: "success",
          });
        })
        .catch(() => {});
    },
    // 测试api
    apiTest() {
      let self = this;
      if (!self.form.httpRequest.length) {
        self.$message({
          message: "请添加API",
          type: "warning",
        });
        return;
      }
      self
        .$confirm("是否确认测试?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(function () {
          let obj = JSON.parse(JSON.stringify(self.form));
          let new_mappingRelation = {};
          obj.dockDataConfig.mappingRelation.map((item, index) => {
            new_mappingRelation[item.column_name] = {
              key: item.column_key,
              type: item.column_type,
              value: item.column_value,
            };
          });
          obj.dockDataConfig.mappingRelation =
            JSON.stringify(new_mappingRelation);
          if (obj.httpRequest) {
            obj.httpRequest.forEach((item) => {
              if (item.body && Object.keys(item.body).length) {
                item.body = JSON.stringify(item.body);
              } else {
                item.body = null;
              }
              if (!item.resultType) {
                item.variables = "";
              }
              delete item.headersMap;
              delete item.parametersMap;
              delete item.variablesMap;
              delete item.bodyMap;
            });
          }
          return testApi(obj);
        })
        .then((res) => {
          self.apiTestData = res.data;
          self.apiTestopen = true;
          self.$message({
            message: "测试成功",
            type: "success",
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    apiTestcancel() {
      this.apiTestopen = false;
      this.apiTestData = [];
    },
    // 执行日志
    excuteLogok(row) {
      this.excuteLogParams.guid = row.guid;
      this.excuteLog();
    },
    excuteLogcancel() {
      this.excuteLogopen = false;
      this.excuteLogParams.pageNum = 1;
      this.excuteLogData = [];
    },
    excuteLog() {
      excuteLog(this.excuteLogParams).then((response) => {
        this.excuteLogData = response.rows;
        this.excuteLogTotal = response.total;
        this.excuteLogopen = true;
      });
    },
    // 接口调用日志
    apiLogok(row) {
      apiLog({ id: row.id }).then((response) => {
        this.apiLogData = response.data;
        this.apiLogopen = true;
      });
    },
    apiLogcancel() {
      this.apiLogopen = false;
      this.apiLogData = [];
    },
    // 打开xPath和jsonPath使用教程
    openTutorials() {
      window.open("https://www.jianshu.com/p/e404edb8c14f", "_blank");
    },
    changeColumntype(item) {
      if (item.column_type === "DYNAMIC") {
        item.column_value = "";
      }
    },
    jsonChange() {
      console.log("json change");
    }, // json数据保存

    jsonSave() {
      console.log("json save");
    }, // 数据错误

    hasError() {
      console.log("has error");
    },
  },
};
</script>
<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
